// 游戏控制器
import { Snake } from './Snake'
import { Food } from './Food'
import { GameModel } from './GameModel'
import { ObjectPool } from '../gamePool/ObjectPool'
import { COLORS, CELL_SIZE, GRID_SIZE } from '../constants/gameConstants'

export class GameController {
  constructor(ctx, width, height, offsetX, offsetY) {
    this.ctx = ctx
    this.width = width
    this.height = height
    this.offsetX = offsetX
    this.offsetY = offsetY
    this.gameModel = new GameModel()
    this.objectPool = new ObjectPool()
    this.init()
  }

  init() {
    this.snake = new Snake()
    this.food = new Food()
    this.lastUpdate = Date.now()
    this.touchStartX = 0
    this.touchStartY = 0
  }

  update() {
    if (this.gameModel.isGameOver || this.gameModel.isPaused) {
      return
    }

    const now = Date.now()
    if (now - this.lastUpdate > 200) { // 控制蛇的移动速度
      this.snake.move()
      
      // 检查是否吃到食物
      if (this.checkFoodCollision()) {
        this.snake.grow()
        this.food.relocate()
        this.gameModel.increaseScore()
      }

      // 检查是否游戏结束
      if (this.snake.checkCollision()) {
        this.gameModel.gameOver()
      }

      this.lastUpdate = now
    }
  }

  render() {
    // 清空画布
    this.ctx.clearRect(0, 0, this.width, this.height)

    // 保存当前上下文状态
    this.ctx.save()
    
    // 移动坐标系到居中位置
    this.ctx.translate(this.offsetX, this.offsetY)

    // 绘制游戏背景
    this.ctx.fillStyle = COLORS.BACKGROUND
    this.ctx.fillRect(0, 0, GRID_SIZE * CELL_SIZE, GRID_SIZE * CELL_SIZE)

    // 绘制网格
    this.drawGrid()

    // 绘制食物
    this.drawFood()

    // 绘制蛇
    this.drawSnake()

    // 恢复上下文状态
    this.ctx.restore()

    // 绘制分数（在游戏区域外）
    this.drawScore()

    // 如果游戏结束，绘制游戏结束界面
    if (this.gameModel.isGameOver) {
      this.drawGameOver()
    }
  }

  drawGrid() {
    this.ctx.strokeStyle = COLORS.GRID
    this.ctx.lineWidth = 0.5
    for (let i = 0; i <= GRID_SIZE; i++) {
      this.ctx.beginPath()
      this.ctx.moveTo(i * CELL_SIZE, 0)
      this.ctx.lineTo(i * CELL_SIZE, GRID_SIZE * CELL_SIZE)
      this.ctx.stroke()

      this.ctx.beginPath()
      this.ctx.moveTo(0, i * CELL_SIZE)
      this.ctx.lineTo(GRID_SIZE * CELL_SIZE, i * CELL_SIZE)
      this.ctx.stroke()
    }
  }

  drawFood() {
    const pos = this.food.getPosition()
    this.ctx.fillStyle = COLORS.FOOD
    this.ctx.fillRect(
      pos.x * CELL_SIZE,
      pos.y * CELL_SIZE,
      CELL_SIZE,
      CELL_SIZE
    )
  }

  drawSnake() {
    this.snake.segments.forEach((segment, index) => {
      this.ctx.fillStyle = index === 0 ? COLORS.SNAKE_HEAD : COLORS.SNAKE_BODY
      this.ctx.fillRect(
        segment.x * CELL_SIZE,
        segment.y * CELL_SIZE,
        CELL_SIZE,
        CELL_SIZE
      )
    })
  }

  drawScore() {
    this.ctx.fillStyle = '#000'
    this.ctx.font = '20px Arial'
    this.ctx.textAlign = 'left'
    this.ctx.fillText(`分数: ${this.gameModel.score}`, this.offsetX, this.offsetY - 10)
  }

  drawGameOver() {
    this.ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'
    this.ctx.fillRect(0, 0, this.width, this.height)

    this.ctx.fillStyle = '#fff'
    this.ctx.font = '40px Arial'
    this.ctx.textAlign = 'center'
    this.ctx.fillText('游戏结束', this.width / 2, this.height / 2 - 40)
    this.ctx.font = '24px Arial'
    this.ctx.fillText(
      `最终得分: ${this.gameModel.score}`,
      this.width / 2,
      this.height / 2 + 10
    )
  }

  handleKeyPress(direction) {
    if (this.gameModel.isGameOver) {
      this.restart()
      return
    }
    this.snake.setDirection(direction)
  }

  handleTouchStart(e) {
    if (this.gameModel.isGameOver) {
      this.restart()
      return
    }
    
    const touch = e.touches[0]
    this.touchStartX = touch.clientX
    this.touchStartY = touch.clientY
  }

  handleTouchMove(e) {
    if (this.gameModel.isGameOver) return

    const touch = e.touches[0]
    const deltaX = touch.clientX - this.touchStartX
    const deltaY = touch.clientY - this.touchStartY

    if (Math.abs(deltaX) > Math.abs(deltaY)) {
      // 水平移动
      if (deltaX > 0) {
        this.snake.setDirection('RIGHT')
      } else {
        this.snake.setDirection('LEFT')
      }
    } else {
      // 垂直移动
      if (deltaY > 0) {
        this.snake.setDirection('DOWN')
      } else {
        this.snake.setDirection('UP')
      }
    }
  }

  handleTouchEnd(e) {
    // 可以添加额外的触摸结束处理逻辑
  }

  checkFoodCollision() {
    const head = this.snake.segments[0]
    const food = this.food.getPosition()
    return head.x === food.x && head.y === food.y
  }

  restart() {
    this.init()
    this.gameModel.resetGame()
  }
}
